<template>
  <el-dialog
    :close-on-click-modal="false"
    :visible.sync="visible"
    class="JADP-dialog JADP-dialog_center transfer-dialog"
    lock-scroll
    width="800px"
    @close="close"
  >
    <div slot="title" style="display: flex">
      共享文件至:
      <el-row style="display: flex; align-items: center">
        <el-col :span="12" :offset="1">
          <el-select
            v-model="organizeId"
            @change="init(documentId)"
            placeholder="请选择"
          >
            <el-option
              v-for="item in options"
              :key="item.id"
              :label="item.fullName"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-col>
        <el-col :span="8" :offset="1">
          <el-radio-group
            v-model="radio"
            style="display: flex"
            @change="handleRadioChange"
          >
            <el-radio label="student">学员</el-radio>
            <el-radio label="clazz">班级</el-radio>
          </el-radio-group>
        </el-col>
      </el-row>
    </div>
    <div
      class="transfer__body"
      v-loading="allLoading"
      :element-loading-text="$t('common.loadingText')"
      style="height: 400px"
    >
      <div class="transfer-pane">
        <div class="transfer-pane__tools">
          <el-input placeholder="输入关键词进行搜索" v-model="keyword">
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="getList"
            ></el-button>
          </el-input>
        </div>
        <div class="transfer-pane__body" style="padding: 10px">
          <el-checkbox-group
            v-model="clazzSelectedData"
            v-if="radio == 'clazz'"
            @change="handleCheckedChange"
          >
            <div v-for="(item, index) in clazzList" style="line-height: 26px">
              <el-checkbox :label="item">{{ item.classname }}</el-checkbox>
            </div>
          </el-checkbox-group>
          <el-checkbox-group
            v-model="personnelList"
            v-else
            @change="personnelListChange"
          >
            <div v-for="(item, index) in list" style="line-height: 26px">
              <el-checkbox :label="item.id"
                >{{ item && item.realname }} /
                {{ item.certificatesnumber }}</el-checkbox
              >
            </div>
          </el-checkbox-group>
        </div>
      </div>
      <div class="transfer-pane">
        <div class="transfer-pane__tools">
          <span>已选</span>
          <el-button @click="removeAll" type="text">清空列表</el-button>
        </div>
        <div class="transfer-pane__body shadow right-pane">
          <template>
            <div
              v-for="(item, index) in selectedData"
              :key="index"
              class="selected-item"
              style="line-height: 32px"
            >
              <!-- <span v-if="radio == 'clazz'">{{ item.stuname }}</span> -->
              <!-- <span v-else>{{ item.realname }} / {{ item.certificatesnumber }}</span> -->
              <span
                >{{ item | screenName(list) }} /
                {{ item | screenCertificatesnumber(list) }}</span
              >
              <i class="el-icon-delete" @click="removeData(item, index)"></i>
            </div>
          </template>
        </div>
      </div>
    </div>

    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">{{
        $t("common.cancelButton")
      }}</el-button>
      <el-button type="primary" @click="dataFormSubmit()">{{
        $t("common.confirmButton")
      }}</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { ShareCreate, ShareCreateClazz } from "@/api/extend/documentFg";
import userTransfer from "@/components/JADP-userTransfer";
import request from "@/utils/request";
import { getOrganizeList } from "@/api/permission/organize";
export default {
  components: { userTransfer },
  data() {
    return {
      visible: false,
      documentId: "",
      selectedData: [], //已选展示列表
      radio: "student",
      allLoading: false,
      keyword: "",
      list: [],
      clazzList: [], //班级list
      clazzSelectedData: [], //已选班级列表
      personnelList: [], //已选人员列表
      personnelList2: [],
      options: [],
      organizeId: "",
    };
  },
  watch: {
    personnelList(newval, oldval) {
      let ab = oldval.filter((o) => !newval.find((o2) => o === o2));
      if (ab.length) {
        let idx = this.selectedData.findIndex((item) => item == ab[0]);
        if (idx !== -1) {
          this.selectedData.splice(idx, 1);
        }
      }
    },
  },
  filters: {
    screenName: function (value, list) {
      if (!value) return "";
      let newArr = list.filter((item) => item.id === value);
      return newArr[0] && newArr[0].realname;
    },
    screenCertificatesnumber: function (value, list) {
      if (!value) return "";
      let newArr = list.filter((item) => item.id === value);
      return newArr[0] && newArr[0].certificatesnumber;
    },
  },
  methods: {
    init(id) {
      if (!id) return;
      this.documentId = id;
      this.visible = true;
      if (!this.organizeId) return;

      this.allLoading = true;

      if (this.radio == "clazz") {
        request({
          url: `/api/xy_ks_class_info/Xy_ks_class_info/getAll/list`,
          method: "post",
          data: {
            classname: this.keyword,
            organizeId: this.organizeId,
          },
        }).then((res) => {
          this.clazzList = res.data;
          // this.shareEvent();
          this.allLoading = false;
        });
      } else {
        request({
          url: `/api/students/Xy_ks_students/getAll/list`,
          method: "post",
          data: {
            realname: this.keyword,
            organizeId: this.organizeId,
          },
        }).then((res) => {
          this.list = res.data;
          this.shareEvent();
          this.allLoading = false;
        });
      }
    },
    // 获取已分享的人员列表
    shareEvent() {
      request({
        url: `/api/extend/FgDocument/ShareUser/${this.documentId}?organizeId=${this.$store.getters.organizeId}`,
        method: "get",
        // data: {
        //   classname: this.keyword
        // }
      }).then((res) => {
        let newArr = [];
        res.data.list.forEach((item) => {
          let foo = this.list.filter((val) => val.id === item.shareUserId);
          if (foo[0]) {
            newArr.push(foo[0].id);
          }
        });
        this.selectedData = newArr.flat();
        this.personnelList = this.selectedData;
      });
    },
    dataFormSubmit() {
      if (!this.selectedData.length) {
        this.$message({
          message: "请选择共享人员",
          type: "error",
          duration: 1000,
        });
        return;
      }
      ShareCreate(
        this.documentId,
        this.selectedData.join(","),
        this.$store.getters.organizeId
      ).then((res) => {
        this.$message({
          message: res.msg,
          type: "success",
          duration: 1500,
          onClose: () => {
            this.visible = false;
            this.$emit("refresh");
          },
        });
      });
    },
    getOrganizeList() {
      getOrganizeList({ organizeId: this.$store.getters.organizeId }).then(
        (res) => {
          this.options = res.data.list;
        }
      );
    },
    // 关键字搜索
    async getList() {
      this.allLoading = true;
      await this.init(this.documentId);
      this.allLoading = false;
    },
    // 清空列表
    removeAll() {
      this.selectedData = [];
      this.personnelList = [];
      this.personnelList2 = [];
      this.clazzSelectedData = [];
    },
    // 单选
    handleRadioChange() {
      // this.selectedData = [];
      // this.keyword = "";
      this.init(this.documentId);
    },
    //删除
    removeData(id, index) {
      this.selectedData.splice(index, 1);
      let idx = this.personnelList.findIndex((item) => item == id);
      if (idx !== -1) {
        this.personnelList.splice(idx, 1);
      }
    },

    //选择人员
    personnelListChange(val) {
      this.personnelList2 = val;
      this.selectedData.push(...val);
      this.selectedData = [...new Set(this.selectedData)];
    },
    //选择班级
    handleCheckedChange(val) {
      let clazzId = val.map((item) => item.id);
      if (val.length) {
        request({
          url: `/api/signuphistory/Xy_ks_signup/infoByClazzId/${clazzId.join()}?organizeId=${this.$store.getters.organizeId}`,
          method: "get",
        }).then((res) => {
          let clazzObj = {};
          this.selectedData = [];

          val.forEach((item) => {
            clazzObj[item.id] = res.data.filter(
              (value) => value.clazzid == item.id
            );
          });
          for (let key in clazzObj) {
            clazzObj[key].forEach((item) => {
              this.selectedData.push(item.stuid);
            });
          }
          this.selectedData.push(...this.personnelList2);
          this.selectedData = [...new Set(this.selectedData)];
          this.personnelList = this.selectedData;
        });
      } else {
        this.selectedData = [];
        this.selectedData.push(...this.personnelList2);
      }
    },
    //关闭
    close() {
      this.$emit("refresh");
    },
  },
  mounted() {
    this.getOrganizeList();
  },
};
</script>

<style scoped lang="scss"></style>
